package com.bootdo.clouddo.controller.book;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.clouddo.redis.CommonRedisService;
import com.bootdo.clouddo.redis.RedisEnum;
import com.bootdo.clouddo.task.BookTask;
import com.bootdo.clouddo.utils.book.BookApi;
import com.bootdo.clouddo.utils.book.BookUtils;
import com.bootdo.clouddo.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/book/v1")
public class ListController {

    @Autowired
    private CommonRedisService redisService;

    @Autowired
    private BookTask bookTask;

    @GetMapping("/list")
    public R getMale(int cateId, String orderBy, int page, int size) {
        try {
            Map params = new HashMap();
            params.put("cateId", cateId);
            params.put("orderBy", orderBy);
            params.put("page", page);
            JSONObject resultVo = BookUtils.fetchJSONObject(BookApi.LIST_BY_CAT.getUrl(), params);
            if(resultVo != null) {
                // 保存
                bookTask.saveDetailArr(resultVo.getJSONArray("list"));
                // 返回数据
                return R.data(resultVo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }

    @GetMapping("/category/{man}")
    public R getCategory(@PathVariable String man) {
        try {
            Optional op = redisService.getAsOptional(RedisEnum.BOOK_CATEGORY.getKey() + man);
            if(op.isPresent()) {
                return R.data(op.get());
            }
            JSONArray resultVo = BookUtils.fetchJSONArray(BookApi.CATEGORYS.getUrl() + man);
            if(resultVo != null && !resultVo.isEmpty()) {
                redisService.put(RedisEnum.BOOK_CATEGORY.getKey() + man, resultVo, RedisEnum.BOOK_CATEGORY.getExpire());
                return R.data(resultVo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }
}
